/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package scheduletask;

import dao.FtpInfoCrud;
import dao.ProviderDao;
import java.io.*;
import java.net.SocketException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import pojo.FtpInfo;
import pojo.Provider;

/**
 *
 * @author Mostafa
 */
public class ScheduleTask {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String username="";
        try {
           
            username=args[0];
            LogFile.log(username , "Start parse file");
            DocumentBuilderFactory dfactory=DocumentBuilderFactory.newInstance();
            DocumentBuilder dbuilder=dfactory.newDocumentBuilder();
            Document xmldocument=dbuilder.parse("config.xml");
             Element settingelement=xmldocument.getDocumentElement();
          String url=settingelement.getElementsByTagName("mysql-url").item(0).getTextContent();
          String mysqlusername=settingelement.getElementsByTagName("mysql-username").item(0).getTextContent();
          String mysqlpassword=settingelement.getElementsByTagName("mysql-password").item(0).getTextContent();
            LogFile.log(username, "get provider information");
            DriverManager.registerDriver(new com.mysql.jdbc.Driver() );
            Connection c=DriverManager.getConnection(url, mysqlusername, mysqlpassword);
            // get provider information and ftp information
            ProviderDao pdao=new ProviderDao(c);
            FtpInfoCrud ftpcrud=new FtpInfoCrud();
            Provider p= pdao.getByName(username);
            FtpInfo ftpinfo=ftpcrud.selectById(p.getPId());
            
            //connect to ftp
           String remoteurl=ftpinfo.getRemoteDir()+File.separator+ftpinfo.getFileName()+"."+ftpinfo.getFileExtension();
           
            FTPClient client=new FTPClient();
       
            client.connect(ftpinfo.getHost());
            System.out.println("Connect.......");
            client.login(ftpinfo.getUserName(), ftpinfo.getPassword());
             System.out.println("Log in.......");
            FTPFile[] files= client.listFiles(remoteurl);
           boolean isgreater=false;
           
           //check if file modified
          
           if(args.length>1)
           {
           String epath=args[1];
           String extractfile=new File(epath).listFiles()[0].getAbsolutePath();
           new ScheduleTask().runScripts(p, extractfile, c);
           new File(".\\"+username+".bat").delete();
           LogFile.log(username, "execute after extraction.");
           
           }
           else
           {
           if(ftpinfo.getDateMod()==null||files[0].getTimestamp().getTime().after( ftpinfo.getDateMod()))
             {     
             
                 boolean iscompressed=new ScheduleTask().isCompressed(ftpinfo.getFileExtension());
                 String path=ftpinfo.getLocalDir();
                 String filepath=ftpinfo.getLocalDir()+File.separator+ftpinfo.getFileName()+"."+ftpinfo.getFileExtension();
              
        
                 File localfile=new File(filepath);
                 FileOutputStream fos=new FileOutputStream(localfile);
                 client.retrieveFile(remoteurl, fos);  
                 
                if(iscompressed)
                {
                
                    String extractpath=path+"\\"+username;
                    File f=new File(extractpath);
                    f.mkdir();
                   
                    String batch=path.split(":")[0] +": \n";
                     batch+="cd \""+path+"\\"+username+"\" \n";
                    String currentdirectory=System.getProperty("user.dir");
                    batch+="\""+currentdirectory+"\\7z\" -y e \""+filepath+"\" \n";
                   
                      batch+="start javaw -jar  \""+currentdirectory+"\\ScheduleTask.jar\" "+username+" \""+extractpath+"\" \n";
                    // batch+="del /f \""+currentdirectory+"\\zzzzz.bat\"  \n ";
                     batch+="exit \n";
                    
                    File batfile=new File(".\\"+username+".bat");
                    FileWriter writer=new FileWriter(batfile);
                    writer.write(batch);
                    writer.close();
                
                       Runtime run=Runtime.getRuntime();
                       run.exec("cmd /c start .\\"+username+".bat");
                        LogFile.log(username, "extract compressed files");
                      
                }
                else{
                new ScheduleTask().runScripts(p, filepath, c);
                
                }       
                   
                 // update modification date of file
                 
                 ftpinfo.setDateMod(new java.sql.Date(files[0].getTimestamp().getTime().getTime()));
                 ftpcrud.update(ftpinfo, ftpinfo.getFtpId());
                 
             }
          
           }
          
            
       
            
        } catch (SAXException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
             LogFile.log(username, ex.getMessage());
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(username, ex.getMessage());
        } catch (SocketException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(username, ex.getMessage());
        } catch (IOException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(username, ex.getMessage());
        } catch (SQLException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(username, ex.getMessage());
        }
        
    }
    
    public  void runScripts(Provider p,String filepath,Connection c)
    {
        try {
            
            LogFile.log(p.getName(), "execute scripts");
            ScriptRunner sr=new ScriptRunner(c, true, false);
         sr.runScript(new FileReader(p.getScriptPath()),p.getName()+"_dim",filepath);
         
         ////////////////   xml work
         DocumentBuilderFactory dfactory=DocumentBuilderFactory.newInstance();
         DocumentBuilder dbuilder=dfactory.newDocumentBuilder();
         Document xmldocument=dbuilder.parse("config.xml");
             Element settingelement=xmldocument.getDocumentElement();
          Element commonelement=(Element)settingelement.getElementsByTagName("common-path").item(0);
     
            String commonpath=commonelement.getTextContent();
          
        
         
         
         ///// end xml
         sr.runScript(new FileReader(commonpath),p.getName()+"_dim",filepath);
         if(p.getType().equalsIgnoreCase("book"))
         {
          Element estimationelement=(Element)settingelement.getElementsByTagName("estimation-path").item(0);
          String estimationpath=estimationelement.getTextContent();
         sr.runScript(new FileReader(estimationpath),p.getName()+"_dim",filepath);
         }
         
        } catch (SAXException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(p.getName(), ex.getMessage());
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
             LogFile.log(p.getName(), ex.getMessage());
        } catch (IOException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
             LogFile.log(p.getName(), ex.getMessage());
        } catch (SQLException ex) {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
             LogFile.log(p.getName(), ex.getMessage());
        }
               
    
    }
    
    public boolean isCompressed(String extension)
    {
    
       
        String[] compressionExtension={"7z" , "deb" , "gz" , "pkg" , "rar" , "sit" , "sitx" ,"Z" ,
            "tar.gz" , "zip" , "zipx" };
        for (int i = 0; i < compressionExtension.length; i++) {
            if(extension.equalsIgnoreCase(compressionExtension[i]))
            {
                return true;
            }
        }
        
        
        return false;
    }
    
    
    
}
